package com.zch.threadpool.mythreadpool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程池里的工作线程,也可以放到线程池里做内部类
 */
public class WorkThread extends Thread {
    private Runnable runnable;//需要执行的线程任务
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    protected boolean first = true;
    private boolean shutdown;

    public WorkThread() {
    }

    public void setRunnable(Runnable runnable) {//设置任务，到线程中
        lock.lock();
        try {
            this.runnable = runnable;//修改任务
            condition.signal();//唤醒start方法(用于非第一次使用的情况)
        } finally {
            lock.unlock();
        }
    }

    public void closeThread() {
        lock.lock();
        try {
            condition.signal();
            shutdown = true;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        lock.lock();
        try {
            first = false;
            while (true) {
                runnable.run();//运行传入的任务
                MyThreadPool.availableThreads.add(this);//任务执行完把线程自己回添加线程阻塞队列中方便其它任务用

                condition.await();//在没有结受到任务时让起阻塞住
                if (shutdown)
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
